package club.itstudio.IContainer.annotation;

import club.itstudio.IContainer.entity.User;
import club.itstudio.IContainer.exception.SessionException;
import club.itstudio.IContainer.service.AuthService;
import club.itstudio.IContainer.service.UserService;
import club.itstudio.IContainer.util.CookieUtil;
import club.itstudio.IContainer.util.Encrypt;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.HashMap;

@Aspect
@Component
@Order(1000)
public class LoginRequiredHandler {
    private final String[] cookieKey = new String[]{"username", "timestamp", "token"};
    private UserService userService;
    private AuthService authService;

    @Around("@annotation(club.itstudio.IContainer.annotation.LoginRequired)")
    public Object loginRequiredHandler(ProceedingJoinPoint joinPoint) throws Throwable {
        HashMap<String, String> cookieMap = CookieUtil.getCookies();
        for (String key : cookieKey) {
            if (!cookieMap.containsKey(key)) throw new SessionException();
        }
        String realToken = Encrypt.encAES(cookieMap.get(cookieKey[0]) + cookieMap.get(cookieKey[1]), Encrypt.AESKey);
        if (!realToken.equals(cookieMap.get(cookieKey[2]))) {
            throw new SessionException();
        }

        User user = userService.getByUserName(cookieMap.get(cookieKey[0]));
        authService.threadLocalUsers.set(user);
        try {
            return joinPoint.proceed();
        }finally {
            authService.threadLocalUsers.remove();
        }
    }


    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @Autowired
    public void setAuthService(AuthService authService) {
        this.authService = authService;
    }
}
